from datetime import datetime, timedelta
import tzlocal
import requests
import csv
import jieba
from os.path import dirname, abspath
from model.applist_ContactExtractor import Applist_ContactExtractor
from model.input_ContactExtractor import Input_ContactExtractor
from sklearn.externals import joblib
from common.logger import Logger
import traceback
from common.exchange_mail_util import ExchangeUtil
from dataflow.conf import notify_emails

logger = Logger("score_util.log").getLogger()

model_path = dirname(dirname(abspath(__file__)))
applist_model = joblib.load(model_path + '/model/applist_lgb_20181119_model.m')
tfidf_model = joblib.load(model_path + '/model/input_tfidf_20181104_model.m')
input_model = joblib.load(model_path + '/model/input_lgb_20181104_model.m')

jieba.initialize()
app_ex = Applist_ContactExtractor()
input_ex = Input_ContactExtractor()

logger.info('score util init')
headers = {'content-type': 'application/json'}
interval_date = 90


def timestamp_datetime(posix_time):
    unix_timestamp = float(posix_time)
    local_timezone = tzlocal.get_localzone()
    return datetime.fromtimestamp(unix_timestamp, local_timezone)


def get_calc_app_score(imei, start_date, end_date):
    """
    author: chenjiannan
    :return: app_score的计算结果
    """
    app_list = get_applist(imei, start_date, end_date)
    if app_list is None or len(app_list) == 0:
        return 1000
    score_app = calc_model_app_score(app_list, imei, start_date, end_date)

    return score_app


def get_applist(imei, start_date, end_date):
    try:
        # 因为出入值位20181207这样的数据所以就不用进行时间戳的转换
        url = 'http://10.144.79.236:9091/finance/v1.0/applist'  # url后续会变化
        payload = {'imei': imei, 'startDate': start_date, 'endDate': end_date}
        response = requests.get(url=url, params=payload)

        if response.status_code == 200:
            res_data = response.json()
            if res_data is not None:
                if res_data['status'] is True:
                    return res_data['data']
    except:
        logger.error(traceback.format_exc())

    return None


# 计算app_score的脚本
def calc_model_app_score(app_list, imei, start_date, end_date):
    """
    author: chenjiannan
    desc: 原本只是需要apply_time，但现在改成了start_date与end_date
    :return:
    """
    apply_date = end_date
    try:
        app_res = app_ex.parse(apply_date, app_list, applist_model)
        return app_res['app_score']
    except:
        logger.error(traceback.format_exc())
        mail = ExchangeUtil('程杨模型app_score算分脚本计算异常', notify_emails)
        mail.set_content(traceback.format_exc())
        mail.send()
    return 1000

def get_calc_input_score(imei, start_date, end_date):
    """
    author: chenjiannan
    :return: input_score的计算结果
    """
    input_data = get_input_data(imei, start_date, end_date)
    if input_data is None or len(input_data) == 0:
        return 1000
    score_input = calc_model_input_score(input_data, imei, start_date, end_date)

    return score_input



def get_input_data(imei, start_date, end_date):
    try:
        url = 'http://10.144.79.236:9091/finance/stat/v1.0/word'
        payload = {'imei': imei, 'startDate': start_date, 'endDate': end_date}
        response = requests.get(url=url, params=payload)

        if response.status_code == 200:
            res_data = response.json()
            if res_data is not None:
                if res_data['status'] is True:
                    return res_data['data']
    except:
        logger.error(traceback.format_exc())

    return None


# 计算input_score的脚本
def calc_model_input_score(input_data, imei, start_date, end_date):
    """
    author: chenjiannan
    :return:
    """
    apply_date = end_date
    try:
        input_res = input_ex.parse(imei, input_data, tfidf_model, input_model)
        return input_res['input_score']
    except:
        logger.error(traceback.format_exc())
        mail = ExchangeUtil('程杨模型input_score算分脚本计算异常', notify_emails)
        mail.set_content(traceback.format_exc())
        mail.send()
    return 1000


# def calc_model_score(app_list, input_data, imei, apply_date):
#     try:
#         app_res = app_ex.parse(apply_date, app_list, applist_model)
#         input_res = input_ex.parse(imei, input_data, tfidf_model, input_model)
#         return app_res['app_score'], input_res['input_score']
#     except:
#         logger.error(traceback.format_exc())
#         mail = ExchangeUtil('程杨模型算分脚本计算异常', notify_emails)
#         mail.set_content(traceback.format_exc())
#         mail.send()
#     return 1000, 1000


# def get_calc_score(output_flag, imei, start_date, end_date, calc_flag=False):
#     input_data, app_list = None, None
#     if calc_flag:
#         if output_flag == 0 or output_flag == 2:
#             app_list = get_applist(imei, start_date, end_date)
#         elif output_flag == 1 or output_flag == 2:
#             input_data = get_input_data(imei)
#         if input_data is None:
#             input_data = []
#
#         if app_list is None:
#             app_list = []
#     else:
#         input_data = get_input_data(imei)
#         if input_data is None or len(input_data) == 0:
#             return None, None
#
#         app_list = get_applist(imei, start_date, end_date)
#         if app_list is None or len(app_list) == 0:
#             return None, None
#
#     score_app, score_input = calc_model_score(app_list, input_data, imei,
#                                               [timestamp_datetime(start_date).strftime('%Y%m%d'),
#                                               timestamp_datetime(end_date).strftime('%Y%m%d')])
#
#     return score_app, score_input

if __name__ == "__main__":
    with open('../data/apply_imei_20181120_format_sort.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        line_count = 0
        for row in csv_reader:
            imei = row[0]
            start_time = row[1]
            end_time = row[2]
            # apply_dt = datetime.strptime(apply_time, '%Y%m%d').strftime("%s")
            # start_time = datetime.now()
            # applist = get_applist(imei, start_time, end_time)
            # applist_cnt=0
            # if applist is not None:
            #     applist_cnt = len(applist)
            #     if applist_cnt > 0:
            #         print([imei, start_time, end_time])
            #         print(applist_cnt)



            input_data = get_input_data(imei, start_time, end_time)
            input_cnt = 0
            if input_data is not None:
                input_cnt = len(input_data)
                if input_cnt > 0:
                    print(imei, start_time, end_time)
            # if line_count % 100 == 0:
            #     print(line_count)
            # line_count += 1

